<?php
namespace app\admin\controller;
use think\facade\Db;
use app\__MODULE__\model\{Seckill as SeckillModel,SeckillDetail,User as UserModel};
use app\common\BaseController;

class Seckill extends BaseController{
    

    /**
     * 首页
     */
    public function index(){
        $page   = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        if(isset($search['title']) && $search['title'] !=''){
            $wheres[] = ['title','like',"%{$search['title']}%"];
        }
        $redis = redis_instance(); $redis = redis_instance();
        $query  = SeckillModel::where($wheres);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
        if(count($data)){
            foreach ($data as $key => $v) {
                $v['start_time'] = date('Y-m-d H:i:s',$v['start_time']);
                $v['end_time'] = date('Y-m-d H:i:s',$v['end_time']);
                $v['redis_stock'] = $redis->lLen("{$this->redis_key}:SeckillStock:{$v['id']}");
            }
        } 
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

        /**
     * 上架/下架操作
     * date 2021/3/17 11:20
     */
    public function is_show() {
        $id      = param_check('id');
        $checked = param_check('checked', 0);
        $res = SeckillModel::where('id', $id)->update([
            'is_show'        => $checked ? 1 : 0,
            'update_time'   => time()
        ]);
        $res ? json_response(1, '修改成功') : json_response(0, '修改失败');
    }

    /**
     * 添加库存
     * @return void
     * @author Sam
     * date 2021-12-03
     */
    public function add_stock() {
        $id = param_check('id');
        $stock = param_check('stock');
        $detail = SeckillModel::find($id);
        $detail->stock += $stock;
        $res = $detail->save();
        if($res){
            $redis = redis_instance();
            $redis->multi(\Redis::PIPELINE);
            for($i=1; $i<=$stock; $i++) {
                $redis->lPush("{$this->redis_key}:SeckillStock:{$id}", 1);
            }
            $redis->exec();
            json_response(1, '添加库存成功');
        }else{
            json_response(0, '添加库存失败');
        }
            
    }


            /**
     * 详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-04-26
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = SeckillModel::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }
        /**
     * 添加
     * @return void
     * @author 
     * date 
     */
    public function create(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'title' => 'require',
                'stock' => 'require',
                'goods_thumb' => 'require',
                'price' => 'require',
            ], [
               'title.require'       => '标题不得为空',
               'stock.require'       => '库存不得为空',
               'goods_thumb.require' => '图片不得为空',
               'price.require'       => '价格不得为空',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
             $data['start_time'] = strtotime($data['start_time']);
             $data['end_time'] = strtotime($data['end_time']);
             if(($data['end_time']) < ($data['start_time'])) json_response(0,'结束时间不得早于开始开始');
           if($res = SeckillModel::create($data)){
                if(!empty($data['stock'])) {
                    $redis = redis_instance();
                    $redis->multi(\Redis::PIPELINE);
                    for($i=1; $i<=$data['stock']; $i++) {
                        $redis->lPush("{$this->redis_key}:SeckillStock:{$res->id}", 1);
                    }
                    $redis->exec();
                }
                json_response(1,'操作成功');
           } 
           json_response(0,'操作失败');
        
    }



    /**
     * 编辑
     * @return void
     * @author 
     * date 
     */
    public function edit(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'id' => 'require',
                'title' => 'require',
                'stock' => 'require',
                'goods_thumb' => 'require',
                'price' => 'require',
            ], [
                'id.require'       => 'id不得为空',
               'title.require'       => '标题不得为空',
               'stock.require'       => '库存不得为空',
               'goods_thumb.require' => '图片不得为空',
               'price.require'       => '价格不得为空',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        $id = \param_check('id');
           $SeckillModel = SeckillModel::find($id);
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
             if($SeckillModel->start_time <= time()){
                 //活动已经开始
                 unset($data['stock']);
                 unset($data['price']);
             }
             if(($data['end_time']) < ($data['start_time'])) json_response(0,'结束时间不得早于开始开始');
           if(SeckillModel::update($data,['id'=>$id])) json_response(1,'操作成功');
           json_response(0,'操作失败');
    }





        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-07-01
     */
    public function delete(){
        $ids = param_check('ids');
        if(!$SeckillModel = SeckillModel::where('id','in',$ids)->select()) json_response(0,'活动不存在');
        if($SeckillModel->delete()) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }



        /**
     * 砍价订单
     * @return [type] [description]
     */
    public function seckill_order(){
        $page   = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $where = [];
        if(!empty($search['aid'])) $where[] = ['aid', '=', $search['aid']];
        if(!empty($search['pay_status']) && $search['pay_status']!='') $where[] = ['pay_status', '=', $search['pay_status']];
        if(!empty($search['user']) && $search['user']!=''){
            $uid = UserModel::where('nickname|mobile','like',"%{$search['user']}%")->column('id');
            if(count($uid)) $where[] = ['uid','in',$uid];
        }
        $query  = SeckillDetail::with(['user','activity'])->where($where)->order('id desc');
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->append(['pay_status'])->select();
        $bargain = SeckillModel::field('id,title')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
            'bargain' => $bargain
        ]);
    }


            /**
     * 导出excell
     * @return void
     * @author Sam
     *
     */
    public function order_export(){
        $search = request()->param();
        $where = [];
        if(!empty($search['aid'])) $where[] = ['aid', '=', $search['aid']];
        if(!empty($search['pay_status']) && $search['pay_status']!='') $where[] = ['pay_status', '=', $search['pay_status']];
        if(!empty($search['user']) && $search['user']!=''){
            $uid = UserModel::where('nickname|mobile','like',"%{$search['user']}%")->column('id');
            if(count($uid)) $where[] = ['uid','in',$uid];
        }
        $query  = SeckillDetail::with(['user','activity'])->where($where)->order('id desc')->append(['pay_status']);
        big_array_to_csv($query,'text.csv',[
            'id'=>'ID',
            'nickname'=>'用户',
            'order_sn'=>'订单号',
            'pay_status'=>'支付状态',
            'create_time'=>'创建时间',
            'price'=>'砍价价格',
            'title' => ['标题',function($row){
                return $row['activity']['title'];
            }]
        ]);
        
    }

}